package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(){
        return "index";
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.GET)
    public String toAddUserser(){

        return "addUser";
    }
    @RequestMapping(value = "/addUser",method = RequestMethod.POST,consumes ="application/json;charset=utf-8" )
    @ResponseBody
    public Boolean addUser(@RequestBody User user){
        if(user == null){
            return false;
        }
        return userService.addUser(user);
    }
    @RequestMapping(value = "/selectUser", method = RequestMethod.GET)
    public String toSelectUser(Model model) {
        model.addAttribute("user", userService.selectAll());
        return "/userList";
    }
    @RequestMapping(value = "/selectByUsername", method = RequestMethod.GET)
    @ResponseBody
    public List<User> selectByUsername(String userName) {
        List<User> user = userService.selectByUsername(userName);
        return user;
    }
    @RequestMapping(value = "/updateUser",method = RequestMethod.GET)
    public String toUpdateUser(Integer id, Model model){
        model.addAttribute("user", userService.selectUserById(id));
        return "updateUser";
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST, consumes = "application/json;charset=utf-8")
    @ResponseBody
    public Boolean updateUser(@RequestBody User user){
        if(user == null){
            return false;
        }
        return userService.addUser(user);
    }

    @RequestMapping(value = "/deleteUser",method = RequestMethod.GET)
    public String deleteUser(Integer id){
        userService.deleteUser(id);
        return "redirect:selectUser";
    }
}
